const { exec, spawn } = require("child_process");
const chalk = require("chalk"),
  { updateProjectJson } = require("./index");

module.exports = (mode, gameName) => {
  let command = null;

  try {
    updateProjectJson(gameName);
    // npm run dev
    if (mode === "-d") {
      // 子进程执行命令
      command = spawn(
        "npx",
        [`webpack-dev-server`, `--env=development`, `--node-env=development`],
        {
          shell: process.platform === "win32",
          cwd: process.cwd(),
        }
      );
    }

    // npm run build
    else if (mode === "-b") {
      // 子进程执行命令
      command = spawn(
        "npx",
        [`webpack`, `--env=production`, `--node-env=development`],
        {
          shell: process.platform === "win32",
          cwd: process.cwd(),
        }
      );
    }

    // 如果命令已经赋值给command
    if (command) {
      command.stdout.on("data", function (data) {
        console.log(chalk.blue(data));
      });

      command.stderr.on("data", function (data) {
        console.log(chalk.yellow(data));
      });

      command.on("exit", function (code) {
        console.log(chalk.green(`====== 子进程退出：${code} ======`));
      });

      command.on("error", function (error) {
        throw new Error(error.toString());
      });
    } else {
      console.log(chalk.red.bold(`====== ls命令赋值失败 ======`));
    }
  } catch (error) {
    throw new Error(error.toString());
  }

  return command;
};
